<?php
 
class NoBusinessBase_Utility_ProfileTimer
{    
 
    protected static $startTimes;
    protected static $endTimes;
    protected static $durations;
 
    /**
     * Private constructor, so objects cannot be constructed from this class
     */
    private function __construct()
    {
 
    }
 
    public static function start($counter = "def")
    {
        $counter = self::filterCounterName($counter);
        if ($counter === "") throw new Exception('Not valid counter name'); 
 
        self::$startTimes[$counter] = microtime();
    }
 
    public static function stop($counter = "def")
    {
        $counter = self::filterCounterName($counter);
        if ($counter === "") throw new Exception('Not valid counter name');
 
        self::$endTimes[$counter] = microtime(); 
        $aA = explode(' ',self::$startTimes[$counter].' '.self::$endTimes[$counter]); //seperate values and put parts in array
        if (!isset(self::$durations[$counter])) self::$durations[$counter] = 0;
        self::$durations[$counter] += (($aA[2]+$aA[3])-($aA[0]+$aA[1])); //calculate and store
 
    }
 
    public static function printTime($counter = "def")
    {
        $counter = self::filterCounterName($counter);
        if ($counter === "") throw new Exception('Not valid counter name');
 
        if (!isset(self::$durations[$counter])) return false;
 
        if($counter != "def")
          return sprintf('Counter '.$counter.': %03.4f Seconds', self::$durations[$counter]);
        else
          return sprintf('%03.4f Seconds', self::$durations[$counter]);        
    }
 
    public static function getTime($counter = "def")
    {
        $counter = self::filterCounterName($counter);
        if ($counter === "") throw new Exception('Not valid counter name');
 
        if (!isset(self::$durations[$counter])) return false;
        return self::$durations[$counter];         
    }
 
    protected static function filterCounterName($counter)
    {
        $filter = new Zend_Filter_Alnum();
        return $filter->filter($counter);
    }
}
